package com.example.agent;

import java.lang.annotation.Annotation;
import java.lang.instrument.Instrumentation;
import java.util.Objects;

public class CostAgent {

    public static void premain(String options, Instrumentation inst) {
        System.out.println("启动时加载自定义探针...");
        inst.addTransformer(new PrintOutTransformer(), true);
    }

    public static void agentmain(String options, Instrumentation inst) {
        System.out.println("动态加载自定义探针...");
        inst.addTransformer(new PrintOutTransformer(), true);
        Class[] allLoadedClasses = inst.getAllLoadedClasses();
        for (Class clazz : allLoadedClasses) {
            Annotation[] declaredAnnotations = null;
            try {
                declaredAnnotations = clazz.getDeclaredAnnotations();
                if (isAnnotationPresent("org.springframework.web.bind.annotation.RestController", declaredAnnotations)) {
                    //重新转换已经加载的目标类，使其生效
                    inst.retransformClasses(clazz);
                }
            } catch (Exception e) {
                //do nothing
            }
        }
    }

    private static boolean isAnnotationPresent(String annotation, Annotation[] annotationArr) {
        if(Objects.isNull(annotationArr)) {
            return false;
        }
        for (Annotation ann : annotationArr) {
            return annotation.equals(ann.annotationType().getName());
        }
        return false;
    }
}
